//
//  AddPatientController.m
//  HarmonizePub
//
//  Created by rzhy on 16/9/22.
//  Copyright © 2016年 Zy. All rights reserved.
//

#import "AddPatientController.h"
#import "Config.h"
#import "JKCountDownButton.h"
#import "Utils.h"
#import "User.h"
#import "Patient.h"
#import <YYModel.h>
#import "SVProgressHUD.h"
#import "WebViewController.h"
#import "QRCodeController.h"

@interface AddPatientController () <UITextFieldDelegate>
{
    NSArray *_array;
}
@property (weak, nonatomic) IBOutlet UISegmentedControl *switchSegmentedControl;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UILabel *numberLabel;
@property (weak, nonatomic) IBOutlet UITextField *phoneField;
@property (weak, nonatomic) IBOutlet UITextField *numberField;
@property (weak, nonatomic) IBOutlet UILabel *codeLabel;
@property (weak, nonatomic) IBOutlet UITextField *codeField;
@property (weak, nonatomic) IBOutlet JKCountDownButton *codeButton;
@property (weak, nonatomic) IBOutlet UIView *codeLineView;
@property (weak, nonatomic) IBOutlet UIButton *sendButton;
@property (nonatomic, strong) AddSuccessBlock addSuccess;
@property (weak, nonatomic) IBOutlet UIButton *qrCodeBindButton;

@end

@implementation AddPatientController

+ (instancetype)addPatientWithAddSuccess:(AddSuccessBlock)addSuccess {
    AddPatientController *addPatient = [[self alloc] init];
    addPatient.addSuccess = addSuccess;
    return addPatient;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"新增就诊人";
    [self setCornerRadiusWithView:self.codeButton];
    [self setCornerRadiusWithView:self.sendButton];
    [self setCornerRadiusWithView:self.qrCodeBindButton];
    
    NSDictionary *oneDict = @{@"number" : @"手机号:", @"numberP" : @"请输入你的手机号", @"label" : @"就诊卡号:", @"placeholder" : @"请输入你的就诊卡号"};
    NSDictionary *twoDict = @{@"number" : @"身份证:", @"numberP" : @"请输入你的身份证号码", @"label" : @"住院号:", @"placeholder" : @"请输入你的住院号"};
    _array = @[oneDict, twoDict];
    [self.nameField becomeFirstResponder];
    if (self.type) {
        self.switchSegmentedControl.userInteractionEnabled = NO;
        self.switchSegmentedControl.selectedSegmentIndex = self.type - 1;
        [self switchSegmentedControlEvent:self.switchSegmentedControl];
    }
}

- (void)setCornerRadiusWithView:(UIView *)view {
    view.layer.cornerRadius = 5.0f;
    view.layer.masksToBounds = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 按钮点击事件
#pragma mark 二维码绑定.
- (IBAction)qrCodeBindEvent {
    QRCodeController *code = [[QRCodeController alloc] init];
    [self.navigationController pushViewController:code animated:YES];
}

#pragma mark 就诊卡绑定说明
- (IBAction)bindExplainEvent {
    NSURL *url = [URLTool webURLStringWithPathString:XHBindExplain token:nil];
    WebViewController *web = [[WebViewController alloc] init];
    web.title = @"就诊卡绑定说明";
    web.url = url;
    [self.navigationController pushViewController:web animated:YES];
}

#pragma mark 获取验证码
- (IBAction)getCodeButtonEvent:(JKCountDownButton *)sender {
    NSString *name = [self.nameField.text stringRemoveSpecialSymbol:@" "];
    NSString *phone = self.phoneField.text;
    NSString *number = self.numberField.text;
    NSInteger type = self.switchSegmentedControl.selectedSegmentIndex + 1;
    if (!name || [name isEqualToString:@""]) {
        [self setAlertViewWithMessage:@"请输入您的姓名!"];
    } else if (!phone || [phone isEqualToString:@""]) {
        [self setAlertViewWithMessage:@"请输入您的手机号!"];
    } else if (phone.length != 11) {
        [self setAlertViewWithMessage:@"请输入正确的手机号!"];
    } else if (!number || [number isEqualToString:@""]) {
        [self setAlertViewWithMessage:@"请输入您的门诊卡号!"];
    } else {
        sender.enabled = NO;
        [sender startCountDownWithSecond:60];
        [sender countDownChanging:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
            countDownButton.backgroundColor = [UIColor lightGrayColor];
            return [NSString stringWithFormat:@"剩余%d秒", (int)second];
        }];
        [sender countDownFinished:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
            countDownButton.enabled = YES;
            countDownButton.backgroundColor = RGBColor(125, 26, 31);
            return @"重新获取";
        }];
        [self.view endEditing:NO];
        [SVProgressHUD show];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
        NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
        NSDictionary *param = @{@"name" : name, @"phone" : phone, @"num" : number, @"type" : @(type)};
        [HTTPSTool POST:XHGetBrda params:param cookie:cookie success:^(NSDictionary * _Nonnull JSON) {
//            XHLog(@"查询卡号 -> JSON: %@", JSON)
            [SVProgressHUD dismiss];
            NSInteger result = [JSON[@"ret"] integerValue];
            if (result > 1) {
                [self setAlertViewWithMessage:JSON[@"msg"]];
                [sender stopCountDown];
            } else if (result == 1) {
                [ZYToast showBottomText:@"验证码发送成功!"];
            } else if (result == -1) {
                // 登录
                [sender stopCountDown];
                [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"XHLogin" object:nil userInfo:nil]];
            } else {
                [sender stopCountDown];
            }
        } failure:^(NSError * _Nonnull error) {
            [SVProgressHUD dismiss];
            [sender stopCountDown];
        }];
    }
}

#pragma mark 提交
- (IBAction)sendButtonEvent:(UIButton *)sender {
    NSInteger index = self.switchSegmentedControl.selectedSegmentIndex;
    if (index) {
        [self bindingZY];
    } else {
        [self bindingMZ];
    }
}

- (void)bindingMZ {
    NSString *name = [self.nameField.text stringRemoveSpecialSymbol:@" "];
    NSString *phone = self.phoneField.text;
    NSString *number = self.numberField.text;
    NSString *code = self.codeField.text;
    if (!name || [name isEqualToString:@""]) {
        [self setAlertViewWithMessage:@"请输入您的姓名!"];
    } else if (!phone || [phone isEqualToString:@""]) {
        [self setAlertViewWithMessage:@"请输入您的手机号!"];
    } else if (phone.length != 11) {
        [self setAlertViewWithMessage:@"请输入正确的手机号!"];
    } else if (!number || [number isEqualToString:@""]) {
        [self setAlertViewWithMessage:@"请输入您的门诊卡号!"];
    } else if (!code) {
        [self setAlertViewWithMessage:@"请输入验证码!"];
    } else {
        NSDictionary *param = @{@"name" : name, @"phone" : phone, @"num" : number, @"code" : code, @"type" : @(1)};
        NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
        __unsafe_unretained AddPatientController *weakSelf = self;
        [HTTPSTool POSTRequestWithPath:XHBindBrda cookie:cookie params:param success:^(NSDictionary * _Nonnull JSON) {
//            XHLog(@"确认绑定就诊卡 -> JSON: %@", JSON)
            [_codeButton stopCountDown];
            [weakSelf getPatientList];
        }];
    }
}

- (void)bindingZY {
    NSString *name = [self.nameField.text stringRemoveSpecialSymbol:@" "];
    NSString *phone = self.phoneField.text;
    NSString *number = self.numberField.text;
    if (!name || [name isEqualToString:@""]) {
        [self setAlertViewWithMessage:@"请输入您的姓名!"];
    } else if (!phone || [phone isEqualToString:@""]) {
        [self setAlertViewWithMessage:@"请输入您的身份证号码!"];
    } else if (phone.length != 18) {
        [self setAlertViewWithMessage:@"请输入正确的身份证号码!"];
    } else if (!number || [number isEqualToString:@""]) {
        [self setAlertViewWithMessage:@"请输入您的门诊卡号!"];
    } else {
        NSDictionary *param = @{@"brxm" : name, @"sfzh" : phone, @"num" : number};
        NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
        __unsafe_unretained AddPatientController *weakSelf = self;
        [HTTPSTool POSTRequestWithPath:XHBindZyBrda cookie:cookie params:param success:^(NSDictionary * _Nonnull JSON) {
//            XHLog(@"确认绑定就诊卡 -> JSON: %@", JSON)
            [weakSelf getPatientList];
        }];
    }
}

#pragma mark - 获取绑定就诊卡列表
- (void)getPatientList {
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    NSDictionary *param = @{@"type" : @"0"};
    [HTTPSTool POSTRequestHidenHUDWithPath:XHGetBrdaList cookie:cookie params:param progress:nil success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"绑定就诊卡列表 -> JSON: %@", JSON)
        [self storagePatientListDataWithDataArray:JSON[@"data"][@"list"]];
    } failure:nil];
}

#pragma mark - 储存就诊列表数据
- (void)storagePatientListDataWithDataArray:(NSArray *)dataArray {
    if (!dataArray.count || !dataArray) return ;
    NSMutableArray *medicalArray = [NSMutableArray array];
    NSMutableArray *inpatientArray = [NSMutableArray array];
    NSString *bindNum = self.numberField.text;
    for (NSDictionary *dataDict in dataArray) {
        if ([bindNum isEqualToString:dataDict[@"bindNum"]])
            [Patient yy_modelWithDictionary:dataDict];
        if ([dataDict[@"bindType"] integerValue] == 1)
            [medicalArray addObject:dataDict];
        else
            [inpatientArray addObject:dataDict];
    }
    NSMutableDictionary *rootDict = [NSMutableDictionary dictionary];
    if (medicalArray.count) [rootDict setValue:medicalArray forKey:XHMedicalListKey];
    if (inpatientArray.count) [rootDict setValue:inpatientArray forKey:XHInpatientLisyKey];
    [rootDict writeToFile:XHPatientListPath atomically:YES];
    
    if (self.addSuccess) {
        [self.navigationController popViewControllerAnimated:NO];
        self.addSuccess();
    } else
        [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)switchSegmentedControlEvent:(UISegmentedControl *)sender {
    [self.view endEditing:NO];
    NSInteger index = sender.selectedSegmentIndex;
    self.codeLabel.hidden = index;
    self.codeField.hidden = index;
    self.codeButton.hidden = index;
    self.codeLineView.hidden = index;
    self.qrCodeBindButton.hidden = !index;
    
    NSDictionary *dict = _array[index];
    self.numberLabel.text = dict[@"number"];
    self.phoneField.placeholder = dict[@"numberP"];
    self.label.text = dict[@"label"];
    self.numberField.placeholder = dict[@"placeholder"];
    if (index) {
        self.phoneField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    } else {
        self.phoneField.keyboardType = UIKeyboardTypeNumberPad;
    }
}

#pragma mark - textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - AlertView
- (void)setAlertViewWithMessage:(NSString *)msg {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:NO];
}

@end
